<?php

namespace App\Admin\Actions\Form;

use App\Models\WpsFormAnswer;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Rap2hpoutre\FastExcel\FastExcel;

class Import extends Action
{
    public $name = '导入数据';

    protected $selector = '.import-post';

    public function handle(Request $request)
    {
        // 验证请求中的文件是否存在
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls,csv',
        ], [
            'file.required' => '请上传文件',
            'file.file'     => '文件不合法',
            'file.mimes'    => '请上传xlsx,xls,csv文件',
        ]);

        $localDir = 'excel/' . date('ymd');
        // 获取上传的文件
        $path = $request->file('file')->store($localDir);
        $localPath = Storage::path($path);
        $wpsFormId = $request->input('wps_form_id');
        // 下面的代码获取到上传的文件，然后使用`maatwebsite/excel`等包来处理上传你的文件，保存到数据库
        try {
            $collection = (new FastExcel())->import($localPath);
            $array = [];
            foreach ($collection as $item) {
                $array[] = [
                    'wps_form_id' => $wpsFormId,
                    'answer'      => json_encode($item, JSON_UNESCAPED_UNICODE),
                    'submit_time' => date('Y-m-d H:i:s'),
                    'event'       => 'import',
                ];
            }
            WpsFormAnswer::query()->insert($array);
        } catch (\Throwable $e) {
            return $this->response()->error('导入异常！' . $e->getMessage())->refresh();
        }

        return $this->response()->success('导入完成！')->refresh();
    }

    public function form()
    {
        $this->file('file', '请选择文件');
        $this->hidden('wps_form_id',)->value(\request()->input('wps_form_id'));
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-post"><i class="fa fa-upload"></i>导入数据</a>
HTML;
    }
}
